class User < ActiveRecord::Base
  belongs_to :compte, :polymorphic => true

  attr_accessor :password
  attr_accessible :email, :password, :password_confirmation

  validates_presence_of :email

  validates_presence_of :password, :on => :create

  validates_length_of :password, :within => 6..40,
                      :unless => Proc.new{ |a| a.password.blank?}

  validates_format_of :email,
                      :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i,
                      :unless => Proc.new{ |a| a.email.blank?}

  validates_uniqueness_of :email,
                          :case_sensitive => false

  validates_confirmation_of :password, :on => :create

  before_create :encrypt_password

  # Return true if the user's password matches the submitted password.
  def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
  end

  def self.authenticate(email, submitted_password)
    user = find_by_email(email)
    return nil  if user.nil?
    return user if user.has_password?(submitted_password)
  end

  def remember_me!
    self.remember_token = encrypt("#{salt}--#{id}--#{Time.now.utc}")
    save_without_validation
  end

  private

  def encrypt_password
    unless password.nil?
      self.salt = make_salt
      self.encrypted_password = encrypt(password)
    end
  end

  def encrypt(string)
    secure_hash("#{salt}#{string}")
  end

  def make_salt
    secure_hash("#{Time.now.utc}#{password}")
  end

  def secure_hash(string)
    Digest::SHA2.hexdigest(string)
  end

end
